home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Resource for Source: C/C++
/
Resource for Source - C-C++.iso
/
codelib9
/
v_11_02
/
curinput.c
< prev
next >
Wrap
C/C++ Source or Header
|
1995-11-01
|
4KB
|
119 lines
/* CURINPUT.C
* Currency format input function
* Uses non-ANSI unbuffered char I/O functions
* W.F.H. Borman
*/
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
#define DOUBLESTRING 16 // Max. 15 digits
double curcy_input(void)
{
char numstr[DOUBLESTRING]; // Number string
int dotflag = 0; // Decimal point flag
int deccntr=0; // Dec. place counter
int ch; // Input character
int i=0; // Pointer in numstr
double number; // Return value
while ((ch=getch()) !='\r') { // Input until CR
if(ch == 0) { // Extended code
getch(); // Discard 2nd part
putch('\a'); // Beep
continue; // Get next input
}
/*** Handle backspace character ***/
if(i>0 && ch=='\b') { // If backspaced
i--; // Decrement pointer
putch('\b'); // Move cursor back
putch(' '); // Erase character
putch('\b'); // Move cursor back
if(deccntr) // If dec.pt. used
deccntr--; // Update dec.counter
if(numstr[i] =='.') // If dec.pt. erased
dotflag = 0; // Reset dec.pt.flag
continue; // Read next character
}
/*** Check validity of character entered: ***/
if(strchr("0123456789-.",ch)) { // Valid chars.
switch(dotflag) { // Dec.pt. entered?
/*** Before decimal point has been entered: ***/
case 0:
if(ch=='-' && i>0) { // Embedded '-'
putch('\a'); // Beep and break
}
else if(i<(DOUBLESTRING-1)) {
putch(ch); // Print digit
numstr[i] = ch; // Add ch to numstr
i++; // Increment pointer
if(ch=='.') // If ch is '.'
dotflag = 1; // Set flag
}
else { // Numstr is full
putch('\a'); // Beep and break
}
break;
/*** After decimal point has been entered: ***/
/*** '.' and '-' are invalid; 2 dec. places max. ***/
case 1:
if(ch=='.' || ch=='-' || deccntr>=2) {
putch('\a'); // Beep and break
}
else if(i<(DOUBLESTRING-1)) {
putch(ch);
numstr[i] = ch;
i++;
deccntr++;
}
else {
putch('\a');
}
} // End switch(dotflag)
continue; // Read next character
} // End if(strchr...)
/*** Invalid ch entered to get this far! ***/
putch('\a'); // Beep
/*** Continue until CR entered: ***/
} // End while((ch=...)
numstr[i] = '\0'; // Terminate string
number = atof(numstr); // Convert to double
return number; // Return number
}
/*** --------------- Test driver ---------------- ***/
main()
{
double currency;
clrscr();
puts("\n\nEnter a currency amount: ");
currency = curcy_input();
printf("\nThat number was %.2f\n", currency);
puts("press a key to continue");
getch();
return 0;
}